package com.like.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.like.adapter.ArticleAdapter;
import com.like.adapter.InfoAdapter;
import com.like.entity.Department;
import com.like.entity.EventWrapper;
import com.like.entity.GeneralResponse;
import com.like.entity.InfoListReq;
import com.like.entity.InfoListResp;
import com.like.hospitalworld.InfoDetailActivity;
import com.like.hospitalworld.MainActivity;
import com.like.hospitalworld.PersonalCenterActivity;
import com.like.hospitalworld.R;
import com.like.hospitalworld.SettingsActivity;
import com.like.hospitalworld.ToolActivity;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.InfoService;
import com.like.network.ResponseCode;
import com.like.network.RetrofitUtil;
import com.like.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.fragment_main_information)
public class MainInformationFragment extends BaseFragment {

    @ViewInject(R.id.article_list)
    PullToRefreshListView mArticleList;
    @ViewInject(R.id.title_icon)
    ImageView mTitleIcon;
    @ViewInject(R.id.title_drop)
    ImageView mTitleDrop;
    @ViewInject(R.id.title)
    TextView mTitle;

    private InfoService mInfoService;
    private ArticleAdapter mArticleAdapter;
    private InfoAdapter mInfoAdapter;
    private int mType;
    private int mCurrentPage = 0;
    private int mPageCount = 15;
    private boolean mIsIndex;
    private Department mCurrentDep;
    private MainActivity mMainActivity;

    @Override
    protected void onCreateView() {
        super.onCreateView();
        setToolbar();
        initList();
        mCurrentDep = m.getCurrentDep();
        mInfoService = RetrofitUtil.getService(InfoService.class);
        setTitle(m.getCurrentDep());
        getInfoList(false);
    }

    public void setIsIndex(boolean isIndex) {
        this.mIsIndex = isIndex;
    }

    private void setTitle(Department dep) {
        if (dep == null)
            return;
        if (dep.name.equals("儿科")) {
            Glide.with(m.mContext.getApplicationContext()).load(R.drawable.pediatrics_sel).asBitmap()
                    .dontAnimate().dontTransform().into(mTitleIcon);
            mTitle.setText("儿科");
            mTitleDrop.setVisibility(View.VISIBLE);
        } else if (dep.name.equals("内科")) {
            Glide.with(m.mContext.getApplicationContext()).load(R.drawable.internal_medicine_sel)
                    .asBitmap().dontAnimate().dontTransform().into(mTitleIcon);
            mTitle.setText("内科");
            mTitleDrop.setVisibility(View.VISIBLE);
        } else if (dep.name.equals("皮科")) {
            Glide.with(m.mContext.getApplicationContext()).load(R.drawable.dermatology_sel)
                    .asBitmap().dontAnimate().dontTransform().into(mTitleIcon);
            mTitle.setText("皮科");
            mTitleDrop.setVisibility(View.VISIBLE);
        } else if (dep.name.equals("其他")) {
            Glide.with(m.mContext.getApplicationContext()).load(R.drawable.others_sel).asBitmap()
                    .dontAnimate().dontTransform().into(mTitleIcon);
            mTitle.setText("其它");
            mTitleDrop.setVisibility(View.VISIBLE);
        }
    }

    private void initList() {
        mArticleList.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mArticleList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage = 0;
                getInfoList(false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage += 1;
                getInfoList(true);
            }
        });
    }

    private void getInfoList(final boolean append) {
        Department dep = m.getCurrentDep();
        if (dep == null || mIsIndex)
            mType = 0;
        else
            mType = dep.id;
        InfoListReq req = new InfoListReq(mType, mCurrentPage, mPageCount);
        Call<GeneralResponse<InfoListResp>> call = mInfoService.getInfoList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<InfoListResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<InfoListResp>> call, Response<GeneralResponse<InfoListResp>> response) {
                mArticleList.onRefreshComplete();
                if (!response.isSuccessful())
                    return;
                GeneralResponse res = response.body();
                if (res.result != ResponseCode.SUCCESS)
                    return;
                List<InfoListResp.InformationBase> infos = response.body().data.informationBaseList;
                if (mIsIndex) {
                    if (mArticleAdapter == null) {
                        mArticleAdapter = new ArticleAdapter(getChildFragmentManager(), m.mContext, infos, mIsIndex);
                        mArticleList.setAdapter(mArticleAdapter);
                    } else
                        mArticleAdapter.update(infos, append);
                } else {
                    if (mInfoAdapter == null) {
                        mInfoAdapter = new InfoAdapter(infos, m);
                        mArticleList.setAdapter(mInfoAdapter);
                    } else
                        mInfoAdapter.update(infos, append);
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<InfoListResp>> call, Throwable t) {
                mArticleList.onRefreshComplete();
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getActivity() instanceof MainActivity)
            mMainActivity = (MainActivity) getActivity();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            setToolbar();
            setTitle(m.getCurrentDep());
            Department currentDep = m.getCurrentDep();
            if (mIsIndex)
                return;
            if (currentDep != null && mCurrentDep != null) {
                if (currentDep.id != mCurrentDep.id) {
                    mCurrentPage = 0;
                    getInfoList(false);
                    mCurrentDep = m.getCurrentDep();
                }
            }
        }
    }

    private void setToolbar() {
        View v = mMainActivity.setToolbar(R.layout.toolbar_info_index);
        x.view().inject(this, v);
    }

    @Event(value = R.id.article_list, type = AdapterView.OnItemClickListener.class)
    private void itemClick(AdapterView<?> parent, View view, int position, long id) {
        position -= 1;
        Object obj;
        InfoListResp.InformationBase info;
        if (mIsIndex) {
            obj = mArticleAdapter.getItem(position);
            if (obj == null)
                return;
            info = (InfoListResp.InformationBase) obj;
        } else {
            obj = mInfoAdapter.getItem(position);
            if (obj == null)
                return;
            info = (InfoListResp.InformationBase) obj;
        }
        EventBus.getDefault().postSticky(new EventWrapper(info, InfoDetailActivity.class,
                InfoDetailActivity.REQUEST_INFO_BASE));
        Intent intent = new Intent(getActivity(), InfoDetailActivity.class);
        startActivity(intent);
    }

    @Event(R.id.personal_center)
    private void personalCenterClick(View v) {
        Intent intent = new Intent(m.mContext, PersonalCenterActivity.class);
        startActivity(intent);
    }

    @Event(R.id.settings)
    private void settingsClick(View v) {
        Intent intent = new Intent(m.mContext, SettingsActivity.class);
        startActivity(intent);
    }

    @Event(R.id.tool)
    private void toolClick(View v) {
        Intent intent = new Intent(m.mContext, ToolActivity.class);
        startActivity(intent);
    }
}
